//
//  YHComposeVC.swift
//  XLWB
//
//  Created by key on 16/7/3.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class YHComposeVC: UIViewController {
    
    //MARK: - 入口
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = themeColor
        //设置导航条
        setNavBar()
        
        
        //添加子控件
        addChildView()
        
        
        //监听键盘改变
        keyboardChangeFrame()
    }
    
    
    //MARK: - 设置导航条
    func setNavBar() {
     
        navigationController?.navigationBar.tintColor = themeColor
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Done, target: self, action: "send")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "cancel")
     
        
        navigationItem.titleView = titleView
        
    }
    
    //取消
    func cancel() {
        
        //取消第一响应者
        composeTextView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //发送
    func send() {
        
//        //蒙版
//        SVProgressHUD.showWithStatus("发送中")
//        
//        //取消composeTextView 第一响应者身份
//        composeTextView.resignFirstResponder()
//        
//        //发送时 禁止点击
//        navigationItem.rightBarButtonItem?.enabled = false
        
        
        //遍历composeTextView富文本
        var resultAtt = ""
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (dict, range, _) -> Void in
            
//            print(dict)
            
//            print(range)
            
            //判断 遍历到的数据 是不是文本附件
            if let att = dict["NSAttachment"] as? YHTextAttachment {
                //是文本附件 
                //获取到emotion
                resultAtt += (att.emotion?.chs ?? "")
                
            }else{
                
                //是文本
                let text = (self.composeTextView.text as NSString).substringWithRange(range)
                
                resultAtt += text
                
            }
   
        }
        
        
            
            
            
        //判断是否有图片
        if composeImageView.imageList.count > 0 { //有图片信息
            
            //发送带图片的信息
            YHNetworkTool.sharedTool.composeUpDataWithImage(resultAtt, imageList: composeImageView.imageList, success: { (request) -> () in
    
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.composeTextView.resignFirstResponder()
                self.dismissViewControllerAnimated(true, completion: nil)
                
                }, failure: { (error) -> () in
            
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    
            })
            
            
            
        }else{//没有图片信息
            
            //发送文本信息
            YHNetworkTool.sharedTool.composeUpData(resultAtt, success: { (request) -> () in
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.composeTextView.resignFirstResponder()
                self.dismissViewControllerAnimated(true, completion: nil)
                }) { (error) -> () in
                    
                    SVProgressHUD.showErrorWithStatus("发送失败")
            }
 
        }

    }
    
    //标题 titleView
    private lazy var titleView: UILabel = {
        
        //用户名
        let name = YHUserAccountTool.sharedUserAccountTool.userAccount?.screen_name ?? ""
        
        //显示文本
        let str = "发微博\n\(name)"
        
        //创建 副文本
        let att = NSMutableAttributedString(string: str)
        
        //设置副文本
        let range = (str as NSString).rangeOfString(name)
        att.addAttributes([NSForegroundColorAttributeName: themeColor, NSFontAttributeName: UIFont.systemFontOfSize(13)], range: range)
        
        
        let label = UILabel()
        //设置label副文本
        label.attributedText = att
        
        label.textAlignment = .Center
        
        label.numberOfLines = 0
        
        label.sizeToFit()
        
        
        return label

    }()
    
    


    //MARK: - 添加子控件
    //MARK: - 懒加载composeTextView
    private lazy var composeTextView: YHComposeTextView = {
        
        let textV = YHComposeTextView()
        
        textV.alwaysBounceVertical = true
        
        textV.backgroundColor = RGB(237, green: 237, blue: 237)
        
        textV.font = UIFont.systemFontOfSize(15)
        
        textV.placeholder = "反馈: 喜乐悲欢，人生无可逃避。不想长大，不愿承担责任，那是孩子气的幼稚行为。只是生活太奔波，太疲惫，总要给自己一点温暖和力量，好更勇敢地去面对未来。想着，也许明天会好些吧？也许明天会好些吧。有个“也许”就够了。值得为此勇敢地奋斗下去，独自走下去。"
        
        textV.delegate = self
        
        return textV
        
    }()
    
    //懒加载composeBarView
    private lazy var composeBarView: YHComposeBarView = {
        
        let composeBarV = YHComposeBarView()
 
        
        return composeBarV
        
    }()
    
    //懒加载composeImage
    private var composeImageView: YHComposeImageView = {
        
        let composeImageV = YHComposeImageView()

        return composeImageV
        
    }()
    
    
    //添加子控件
    func addChildView() {
        
        //首次进入 还没有图片的时候 隐藏图片 composeImageView
        composeImageView.hidden = true
        
        //添加
        view.addSubview(composeTextView)
        view.addSubview(composeBarView)
        composeTextView.addSubview(composeImageView)
        
        //闭包调用
        closure()
        
        
        //设置约束
        //文本
        composeTextView.snp_makeConstraints { (make) -> Void in
            
            make.top.leading.trailing.bottom.equalTo(view)
        }
        
        //bar
        composeBarView.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(view)
            
            make.height.equalTo(44)
            
        }
        
        
        //图片composeImage
        composeImageView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(composeTextView).offset(100)
            make.leading.equalTo(composeTextView).offset(10)
            make.size.equalTo(CGSize(width: screenW - 20, height: screenW - 20))
            
        }
        
    }
 
    //MARK: - 点击实现闭包
    func closure() {
        //实现点击bar 图片按钮button 调用的闭包
        composeBarView.composeBarClosure = {[weak self] (type: composeBarViewType) -> () in
            
            //实现功能
            switch type {
                
            case .PictureType:
                //                print("PictureType")
                self?.pictureButton()
                
            case .MentionType:
                print("MentionType")
                
            case .TrendType:
                print("TrendType")
                
            case .EmoticonType:
                
                //设置composeTextView为第一响应者
                self!.composeTextView.becomeFirstResponder()
                
                //判断当前键盘是自定义 还是 系统的 切换
                if self!.composeTextView.inputView == nil {//系统的 切换成自定义
                    
                    //切换inoutView
                    self!.composeBarView.isEmoticon = true
        
                    self!.composeTextView.inputView = YHEmotionView()
                    
                    
                }else{//自定义的 切换成系统的
                    
                    //切换inputView
                    self!.composeBarView.isEmoticon = false
                    
                    self!.composeTextView.inputView = nil
                    
                }
                
                //刷新
                self?.composeTextView.reloadInputViews()
                
            case .AddType:
                print("AddType")
                
            }
            
        }
        
        
        //点击composeImageViewcell + 号  调用
        composeImageView.composeImageClosure = {[weak self] in
            
            self?.pictureButton()
            
        }
    }
    
    
    
    //MARK: - 通知监听键盘frame的改变
    func keyboardChangeFrame() {
        
        //键盘Frame的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
        //监听表情键盘 删除按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionDeleteButtonClick", name: EmotionDeleteNoti, object: nil)
        
        
        //监听表情键盘 表情的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionButtonClick:", name: EmotionButtonNoti, object: nil)
    }
    
    //键盘frame 改变响应方法
    func keyboardWillChangeFrame(noti: NSNotification) {
        
        //获取键盘对象
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        //重新对bar约束
        composeBarView.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view).offset(rect.origin.y - screenH)
        }
        
        //刷新约束
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }

    }
    
    //点击表情键盘删除按钮 响应方法
    func emotionDeleteButtonClick() {
        
//        print("点击表情删除")
        
        //删除光标前一个
        composeTextView.deleteBackward()
        
    }
    
    //点击表情 响应方法
    func emotionButtonClick(noti: NSNotification) {
        
//        print("点击表情")
        //判断传递的参数 是否是YHEmotionModel类型 并且是否有数据
        guard let emotion = noti.object as? YHEmotionModel else {
            
            return
        }
        
        //有数据
        //判断是什么表情
        if emotion.isEmoji {
            //是emoji
            composeTextView.insertText((emotion.code ?? "").emoji())
            
        }else{
            //是其他表情
            
            //1.-->获取composeTextView已经有的文本
            let oldAtt = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            //2.-->创建文本附件
            let att = YHTextAttachment()
            att.emotion = emotion
            
            //设置文本附件 图片
            att.image = UIImage(named: "\(emotion.path ?? "")\(emotion.png ?? "")", inBundle: YHEmotionData.shareEmotion.emotionBundle, compatibleWithTraitCollection: nil)

            //设置文本附件bounds
            let wh = composeTextView.font!.lineHeight //字的高度
            att.bounds = CGRectMake(0, -4, wh, wh)
            
            //根据文本附件创建不可富文本
            let attr = NSAttributedString(attachment: att)
            
            
            //3.-->获取光标
            let selectedRange = composeTextView.selectedRange
            
            
            //4.--> 将光标位置 替换成文本附件
            oldAtt.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            
        
            
            //5.--> 设置富文本font
            oldAtt.addAttributes([NSFontAttributeName: composeTextView.font!], range: NSRange(location: 0, length: oldAtt.length))
            
            
            //6.--> 富文本 返回个 composeTextView
            composeTextView.attributedText = oldAtt
            
            
            //重新赋值完毕 将光标 后移一位
            composeTextView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            
            //7. 点击表情后已经有值了 可以取消placeholder显示了
            //发送通知告诉系统 composeTextView 已经有改变了
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //8. 显示导航条 左边发送按钮
            self.textViewDidChange(composeTextView)
        }
        
        
        
        
    }
    
    
    //MARK: - deinit
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}





//MARK: - 监听composeTextView的改变
extension YHComposeVC: UITextViewDelegate {
    
    
    //改变时调用
    func textViewDidChange(textView: UITextView) {
        
        //判断  有内容 则可以点击发送按钮 动态改变
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    
    //滚动时
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        //取消第一响应者
        composeTextView.resignFirstResponder()
    }
    
    
    
}


//MARK: - 实现bar点击 实现功能
extension YHComposeVC: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    //MARK: - 点击图片
    //点击 响应事件
    func pictureButton() {
        
        let imagePicker = UIImagePickerController()
        
        imagePicker.delegate = self
        
        presentViewController(imagePicker, animated: true, completion: nil)
        
    }
    
    //代理实现选中点击 相册中图片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //压缩图片 方式二:
//        //按照比例压缩造成二进制数据  大小没变化
//        let data = UIImageJPEGRepresentation(image, 0.1)
//        //把二进制数据 转换成图片
//        let imgda = UIImage(data: data!)
        
        
        //压缩图片 方式一: 图形上下文 大小改变
        let img = compressorImage(500, image: image)
        
        //赋值
        composeImageView.comCellImage = img
        
        //实现点击图片方法后 系统不会帮我们返回控制器  因此要自己手动返回
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    //压缩图片
    func compressorImage(width: CGFloat, image: UIImage) -> UIImage {
        
        //1.-- 判断 如果 图片的宽度比指定宽度还短 则不进行压缩 直接返回
        if image.size.width < width {
            
            return image
        }
        
        //2.-- 图片宽度 比 指定宽度 大
        //获取压缩高度  按照压缩后的宽度 和原宽度比 压缩比例
        let imgH = width / image.size.width * image.size.height
        
        //按照绘图 创建图形上下文 进行压缩
        let rect = CGRect(x: 0, y: 0, width: width, height: imgH)
        //--> 创建上下文
        UIGraphicsBeginImageContext(rect.size)
        //--> 将图片渲染到图形上下文
        image.drawInRect(rect)
        //--> 获取图形上下文内容
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //--> 关闭图形上下文
        UIGraphicsEndImageContext()
        
        //返回
        return result
    }
}
